package com.huxiu.pagers.zixun;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.DetailActivity;
import com.huxiu.R;
import com.huxiu.base.ZiXunDetailPager;
import com.huxiu.holder.TuiJianHolder;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.TopImage;
import com.huxiu.net.model.TuiJianItem;
import com.huxiu.net.responses.TopImageListResponse;
import com.huxiu.net.responses.TuiJianDataResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.ErrorResponseException;
import com.huxiu.utils.ImageLoaderOptions;
import com.huxiu.utils.Loading;
import com.huxiu.utils.NetUtil;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.huxiu.view.RefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class TuiJian extends ZiXunDetailPager {

    @ViewInject(R.id.vp_tabdetail_topPhoto)
    private ViewPager vp_tabdetail_topPhoto;//  顶部轮播图

    @ViewInject(R.id.tv_tabdetail_photoinfo)
    private TextView tv_tabdetail_photoinfo;// 图片描述信息
    @ViewInject(R.id.ll_tabdetail_points)
    private LinearLayout ll_tabdetail_points;// 顶部轮播图的点
    @ViewInject(R.id.lv_tabdetail_list)
    private RefreshListView lv_tabdetail_list;// 新闻列表

    @ViewInject(R.id.loading)
    private LinearLayout loading;// 加载中

    @ViewInject(R.id.reLoadView)
    private LinearLayout reLoadView;

    private int preRedPointIndex;// 记录前一个红点的位置
    private Runnable runnable;
    private Handler handler;

    public TuiJian(Context context) {
        super(context);

    }


    private int currentPage = 0;

    @Override
    protected View initView() {
        View viewAll = View.inflate(mContext, R.layout.list_detail, null);
        ViewUtils.inject(this, viewAll);
        //创建顶部轮播图布局对象
        View topNews = View.inflate(mContext, R.layout.topnews, null);
        ViewUtils.inject(this, topNews);

        // 把顶部轮播图添加到Listview身上
        lv_tabdetail_list.addHeaderView(topNews);
        // 给下拉刷新Listview设置监听器
        lv_tabdetail_list.setOnRefreshingListener(new MyOnRefreshingListener());
        // 监听新闻条目点击事件
        //        lv_tabdetail_list.setOnItemClickListener(new MyOnItemClickListener());
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                //要做的事情
                reLoadView.setVisibility(View.VISIBLE);
                loading.setVisibility(View.INVISIBLE);
            }
        };
        return viewAll;
    }


    @Override
    public void initData() {
        if (!NetUtil.checkNet(mContext)) {
            Utils.showToast(R.string.generic_check);
            reLoadView.setVisibility(View.VISIBLE);
            loading.setVisibility(View.INVISIBLE);
            lv_tabdetail_list.setVisibility(View.GONE);
            return;
        }else {
            reLoadView.setVisibility(View.GONE);
            loading.setVisibility(View.VISIBLE);
            lv_tabdetail_list.setVisibility(View.VISIBLE);
        }
        // 获取新闻业务详情数据
        loadtopImage();
        getDataFromServer();
        //        new Handler().postDelayed(new Runnable() {
        //            public void run() {
        //                reLoadView.setVisibility(View.VISIBLE);
        //                loading.setVisibility(View.INVISIBLE);
        //            }
        //        }, 10000);
        handler.postDelayed(runnable, Constants.TIME_RELOADE);
    }

    @OnClick({R.id.reLoadView})
    public void mOnClick(View v) {
        switch (v.getId()) {
            case R.id.reLoadView:
                //                handler.postDelayed(runnable, 5000);//每两秒执行一次runnable
                reLoadView.setVisibility(View.GONE);
                loading.setVisibility(View.VISIBLE);
                lv_tabdetail_list.setVisibility(View.VISIBLE);
                initData();
                break;
        }
    }

    private boolean isRefresh = false;// 当前是否是下拉刷新

    private boolean isLoadMore = false;// 当前是否是加载更多


    class MyOnRefreshingListener implements RefreshListView.OnRefreshingListener {
        @Override
        public void onRefreshing() {
            isRefresh = true;
            // 下拉刷新业务
            getDataFromServer();
        }

        @Override
        public void onLoadingMore() {
            if (currentPage <= totalPages) {
                isLoadMore = true;
                // 加载更多业务
                getMoreDataFromServer();
            } else {
                lv_tabdetail_list.loadMoreFinished();
                Utils.showToast("亲，没有更多数据了");
            }
        }

    }

    //上拉加载
    private void getMoreDataFromServer() {
        loadList(currentPage + 1);
    }

    //下拉刷新
    private void getDataFromServer() {
        loadList(0);


    }

    private List<TuiJianItem> lists = new ArrayList<>();
    private int totalPages = 0;

    //获取推荐页列表页数据
    private void loadList(final int page) {
        String url = NetworkConstants.GET_FEED_ARTICLE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        GsonRequest<TuiJianDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                TuiJianDataResponse.class, true, params,
                new Response.Listener<TuiJianDataResponse>() {
                    @Override
                    public void onResponse(TuiJianDataResponse response) {
                        if (response.isSuccess()) {
                            handler.removeCallbacks(runnable);
                            loading.setVisibility(View.INVISIBLE);
                            reLoadView.setVisibility(View.GONE);
                            if (page == 0 || page == 1) {
                                lists.clear();
                            }
                            Collections.addAll(lists, response.data.datalist);
                            currentPage = response.data.cur_page;
                            totalPages = response.data.total_page;
                            parseListJson(lists);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(true);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;

                            }
                        } else {
                            Utils.showToast(response.error.message);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(false);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Throwable t = error.getCause();
                if (t instanceof ErrorResponseException) {
                    //                Log.e("params", "message" + error.getMessage().toString());
                    Utils.showToast(R.string.generic_failure);
                } else {
                    Utils.showToast(R.string.generic_check_online);
                }

                //                reLoadView.setVisibility(View.VISIBLE);
                //                reLoadView.setVisibility(View.VISIBLE);
                //                loading.setVisibility(View.INVISIBLE);
                if (lists != null && lists.size() > 0) {
                    handler.removeCallbacks(runnable);
                }
                Loading.closeLoading();
                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                if (isRefresh) {
                    lv_tabdetail_list.refreshFinished(false);
                    isRefresh = false;
                } else if (isLoadMore) {
                    lv_tabdetail_list.loadMoreFinished();
                    isLoadMore = false;
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    private void parseListJson(List<TuiJianItem> lists) {
        if (!isLoadMore) {
            adapter = new SpareAdapter();
            lv_tabdetail_list.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private List<TopImage> comments = new ArrayList<>();

    private void loadtopImage() {
        String url = NetworkConstants.GET_FOCUS_ARTICLE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        GsonRequest<TopImageListResponse> request = new GsonRequest<>(url, Request.Method.POST,
                TopImageListResponse.class, true, params,
                new Response.Listener<TopImageListResponse>() {
                    @Override
                    public void onResponse(TopImageListResponse response) {
                        if (response.isSuccess()) {
                            comments.clear();
                            Collections.addAll(comments, response.data);
                            parseTopJson(comments);
                        } else {
                            Utils.showToast(response.error.message);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(R.string.generic_failure);
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }


    protected void parseTopJson(List<TopImage> comments) {
        // 给顶部轮播图设置数据
        vp_tabdetail_topPhoto.setAdapter(new TopAdapter(comments));
        // 监听顶部轮播图
        vp_tabdetail_topPhoto.setOnPageChangeListener(new TopOnPageChangeListener());
        // 初始化第一页图片描述
        tv_tabdetail_photoinfo.setText(comments.get(0).title);
        // 先清空以前的点
        ll_tabdetail_points.removeAllViews();
        // 重新给前一个点赋值
        preRedPointIndex = 0;
        // 添加顶部轮播图里面的点
        for (int i = 0; i < comments.size(); i++) {
            ImageView imageView = new ImageView(mContext);
            imageView.setBackgroundResource(R.drawable.topnews_point_selector);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Utils.dip2px(6),
                    Utils.dip2px(6));
            params.leftMargin = Utils.dip2px(6);
            imageView.setLayoutParams(params);
            imageView.setEnabled(false);
            ll_tabdetail_points.addView(imageView);
        }
        ll_tabdetail_points.getChildAt(0).setEnabled(true);

        //            // 给新闻列表设置数据
        //            adapter = new NewsAdapter();
        //            lv_tabdetail_list.setAdapter(adapter);


        //        // 开启无限轮播
        //        if (handler == null) {
        //            handler = new MyHandler();
        //        }
        //        // 清除之前的消息
        //        handler.removeCallbacksAndMessages(null);// null 是把所有的消息包括callback删除掉
        //        handler.sendMessageDelayed(Message.obtain(handler), 3000);
    }

    SpareAdapter adapter;

    private class SpareAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Object getItem(int position) {
            return lists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TuiJianHolder holder;
            View view = convertView;
            if (view == null) {
                view = View.inflate(mContext, R.layout.item_home_list, null);
                holder = new TuiJianHolder(view, mContext, position);
                view.setTag(holder);
            }
            holder = (TuiJianHolder) view.getTag();
            TuiJianItem item = lists.get(position);
            holder.setAdapter(adapter);
            holder.bindItem(item);//这里用来把获取到的数据传递给holder
            return view;
        }
    }

    class TopOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int position) {
            // 把前一个红点变为白色
            ll_tabdetail_points.getChildAt(preRedPointIndex).setEnabled(false);
            // 根据选中的位置更新图片描述信息
            tv_tabdetail_photoinfo.setText(comments.get(position).title);
            // 根据选中的位置把点变红色
            ll_tabdetail_points.getChildAt(position).setEnabled(true);
            // 给前一个点赋值
            preRedPointIndex = position;
        }
    }

    class TopAdapter extends PagerAdapter {
        List<TopImage> images;

        public TopAdapter(List<TopImage> images) {
            this.images = images;
        }

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = new ImageView(mContext);
            container.addView(imageView);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ImageLoader.getInstance().displayImage(
                    images.get(position).pic_path + Constants.IMAGE_WEBP, imageView, ImageLoaderOptions.options);
            // 监听图片的触摸事件
            imageView.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            // 用户手指按下，停止无限轮播
                            //                            handler.removeCallbacksAndMessages(null);
                            break;
                        case MotionEvent.ACTION_UP:
                            Intent intent = new Intent(mContext, DetailActivity.class);
                            intent.putExtra(Constants.TUIJIAN_ITEM_KEY, images.get(position).toString());
                            mContext.startActivity(intent);
                            switch (position) {
                                case 0:
                                    UmenEvent.UmengEventMap(mContext, UmenEvent.APP_HOME, UmenEvent.HOME_BANNER_1);
                                    break;
                                case 1:
                                    UmenEvent.UmengEventMap(mContext, UmenEvent.APP_HOME, UmenEvent.HOME_BANNER_2);
                                    break;
                                case 2:
                                    UmenEvent.UmengEventMap(mContext, UmenEvent.APP_HOME, UmenEvent.HOME_BANNER_3);
                                    break;
                                case 3:
                                    UmenEvent.UmengEventMap(mContext, UmenEvent.APP_HOME, UmenEvent.HOME_BANNER_4);
                                    break;
                                default:
                                    break;
                            }
                            // 用户手指抬起，继续无限轮播   //实现轮播取消注释就可以
                            //                            handler.sendMessageDelayed(Message.obtain(handler), 3000);
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            // 用户事件取消，继续无限轮播    //实现轮播取消注释就可以
                            //                            handler.sendMessageDelayed(Message.obtain(handler), 3000);
                            break;
                    }
                    return true;// 要想接受move up 事件，必须消费调down事件
                }
            });
            return imageView;
        }
    }

    //    private MyHandler handler;
    //
    //    class MyHandler extends Handler {
    //        @Override
    //        public void handleMessage(Message msg) {
    //            // 判断当前轮播图ViewPager是否还显示在界面上，如果不显示，就不再发消息了
    //            if (vp_tabdetail_topPhoto.getWindowVisibility() == View.GONE) {
    //                handler.removeCallbacksAndMessages(null);
    //                return;
    //            }
    //            // 3s后收到消息，把轮播图切换到下一张
    //            int nextIndex = (vp_tabdetail_topPhoto.getCurrentItem() + 1) % comments.size();
    //            vp_tabdetail_topPhoto.setCurrentItem(nextIndex);
    //            // 再发一个3s的延迟消息，实现无限轮播
    //
    //
    //            //实现轮播取消注释就可以
    //            //            handler.sendMessageDelayed(Message.obtain(handler), 3000);
    //        }
    //    }
    //

}
 